﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Intorise.Common;
using System.Threading;
using Intorise.Net;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
using Microsoft.Office.Interop.Excel;
using Model;
using System.Reflection;

namespace FreightInfoValidator
{
    public partial class MainWindow : Form
    {
        readonly int ORDER_INDEX = 12;//运单号索引
        readonly int STATUS_INDEX = 13;//状态索引
        readonly int INFO_INDEX = 14;//货运信息索引
        readonly int LOGISTICAL_URL_INDEX = 15;//物流网址索引
        List<Country> countries = new List<Country>();
        List<DataInfo> datas = new List<DataInfo>();
        NetTools tools = new NetTools(30);
        bool processing = false;
        DateTime beginTime = DateTime.Now;
        WebClient client = new WebClient();

        public MainWindow()
        {
            InitializeComponent();
            Form.CheckForIllegalCrossThreadCalls = false;
            InitData();
            if (DateTime.Now.Hour < 6)
            {
                ShowStatus("凌晨了还不休息！");
            }
            else if (DateTime.Now.Hour < 12)
            {
                ShowStatus("早上好，宝贝，记得吃早餐！");
            }
            else if (DateTime.Now.Hour < 18)
            {
                ShowStatus("中午好，宝贝，休息会吧！");
            }
            else
            {
                ShowStatus("晚上好，早点休息哦！");
            }
        }

        private void InitData()
        {

        }

        private void 加载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var result = this.ofd.ShowDialog();
            if (result == DialogResult.OK)
            {
                datas.Clear();
                List<string> errorFiles = new List<string>();
                foreach (string f in ofd.FileNames)
                {
                    try
                    {
                        DataInfo info = new DataInfo();
                        info.ExceFile = new FileInfo(f);
                        info.Table = OfficeTools.GetDataTableFromExcel(f, "[划款审单下载$]");
                        info.Table.TableName = "[划款审单下载$]";
                        for (int i = 0; i < info.Table.Columns.Count; i++)
                        {
                            if (info.Table.Rows[0][i].ToString() != "")
                            {
                                info.Table.Columns[i].ColumnName = info.Table.Rows[0][i].ToString();
                            }
                        }
                        info.Table.Rows.RemoveAt(0);
                        datas.Add(info);
                    }
                    catch (Exception ex)
                    {
                        errorFiles.Add(f); MessageBox.Show(ex.Message);
                    }
                }

                if (errorFiles.Count > 0)
                {
                    MessageBox.Show("以下文件没有加载成功，可能格式有误，请联系开发者！\r\n" + string.Join("\r\n", errorFiles));
                }
                ShowMessageLine(string.Format("成功加载了{0}个文件！", datas.Count));
            }
        }

        private void 开始ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.datas.Count == 0)
            {
                MessageBox.Show("请先加载电子表格文件！"); return;
            }
            this.processing = true;
            this.加载ToolStripMenuItem.Enabled = false;
            this.开始ToolStripMenuItem.Enabled = false;
            this.btnLoad.Enabled = false;
            this.btnProcess.Enabled = false;
            this.btnConfig.Enabled = false;
            Thread thread = new Thread(new ParameterizedThreadStart(process));
            thread.Start();
            beginTime = DateTime.Now;
            ShowStatus("正在处理，请稍候！");
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Lu_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (processing && MessageBox.Show("正在处理数据，是否确定要退出？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
            {
                e.Cancel = true;
            }
        }

        private void process(object obj)
        {
            this.progress.Minimum = 0;
            this.progress.Maximum = this.datas.Sum(x => x.Table.Rows.Count);

            datas.ForEach(x =>
            {
                if (!x.ExceFile.Exists) { ShowMessageLine(string.Format("文件{0}不存在，跳过了", x.ExceFile.FullName)); return; }
                int index = 0;
                ShowMessageLine(string.Format("开始处理文件{0}...", x.ExceFile.FullName));
                foreach (DataRow row in x.Table.Rows)
                {
                    int retryCount = 0;
                    this.progress.Value++;
                    index++;
                Start:
                    ShowStatus(string.Format("正在处理{0}/{1}...", this.progress.Value, this.progress.Maximum));
                    string orderNo = null;
                    try
                    {
                        if (row[0] is DBNull || row[0].ToString() == "" || row[0].ToString() == "商户号")
                        {
                            continue;
                        }
                        orderNo = row[ORDER_INDEX].ToString().Trim().ToUpper();

                        string status = row[STATUS_INDEX].ToString();
                        string info = row[INFO_INDEX].ToString();

                    }
                    catch (Exception ex)
                    {
                        if (retryCount < 1)
                        {
                            retryCount++;
                            ShowMessageLine(string.Format("处理{0}的第{1}行数据时出现错误，单号{2}，重试...", x.ExceFile.FullName, index, orderNo));
                            ShowMessageLine(ex.Message);
                            goto Start;
                        }
                        else
                        {
                            ShowMessageLine(string.Format("处理{0}的第{1}行数据时出现错误，单号{2}的数据被跳过。", x.ExceFile.FullName, index, orderNo));
                            ShowMessageLine(ex.Message);
                            row[STATUS_INDEX] = "出错跳过";
                        }
                    }
                    Thread.Sleep(100);
                }
                try
                {
                    var dir = Directory.CreateDirectory(x.ExceFile.Directory + "\\已处理");
                    OfficeTools.TableToExcelFile(x.Table, dir.FullName + "\\已处理_" + x.ExceFile.Name, AppDomain.CurrentDomain.BaseDirectory + "\\templete.xls");
                    ShowMessageLine(string.Format("文件{0}以保存。", x.ExceFile.FullName));
                }
                catch (Exception ex)
                {
                    ShowMessageLine(string.Format("保存文件{0}时出现错误：", x.ExceFile.FullName));
                    ShowMessageLine(ex.Message);
                }
            });
            var time = DateTime.Now - beginTime;
            ShowMessageLine(string.Format("全部加载的{0}个文件约{1}条数据已经处理完成，用时：{2}，速度：{3}个/小时！",
                datas.Count, this.progress.Maximum, time.ToString(), Math.Round(this.progress.Maximum / time.TotalHours)));
            ShowStatus("处理完成！");

            this.加载ToolStripMenuItem.Enabled = true;
            this.开始ToolStripMenuItem.Enabled = true;
            this.btnLoad.Enabled = true;
            this.btnProcess.Enabled = true;
            this.btnConfig.Enabled = true;
            this.processing = false;
            this.progress.Value = 0;
        }

        private void ShowMessage(string text)
        {
            this.richTextBox1.AppendText(text);
        }
        private void ShowMessageLine(string text)
        {
            this.richTextBox1.AppendText(text + "\r\n");
        }
        private void ShowStatus(string text, bool appendMessage = false)
        {
            this.toolStripStatusLabel1.Text = text;
            if (appendMessage)
            {
                ShowMessageLine(text);
            }
        }

        private void Lu_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)  //判断是否最小化
            {
                this.ShowInTaskbar = false;  //不显示在系统任务栏
                notifyIcon1.Visible = true;  //托盘图标可见
            }
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.BringToFront();
        }

        private void ProcessColor(DataInfo dataInfo, DirectoryInfo dir)
        {
            string excelFilename = dataInfo.ExceFile.Directory + "\\已处理\\已处理_" + dataInfo.ExceFile.Name;
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Workbooks wbks = app.Workbooks;
            _Workbook _wbk = wbks.Add(excelFilename);
            Sheets shs = _wbk.Sheets;
            _Worksheet _wsh = (_Worksheet)shs.get_Item(1);
            //((Range)_wsh.Rows[1, Missing.Value]).Interior.ColorIndex = 3;

            DateTime time;
            for (int i = 0; i < dataInfo.Table.Rows.Count; i++)
            {
                //string resultText = dataInfo.Table.Rows[i][INFO_INDEX].ToString().ToLower();
                if (((Range)_wsh.Cells[i + 3, STATUS_INDEX + 1]).Value == "n")
                {
                    continue;
                }
                var value = ((Range)_wsh.Cells[i + 3, INFO_INDEX + 1]).Value;
                if (value == null) { continue; }
                string resultText = value.ToString().ToLower();

                if (DateTime.TryParse(dataInfo.Table.Rows[i]["交易时间"].ToString(), out time) && dataInfo.QueryResult[i].ShipDate.HasValue)
                {
                    if (time > dataInfo.QueryResult[i].ShipDate.Value)
                    {
                        ((Range)_wsh.Cells[i + 3, INFO_INDEX + 1]).Interior.ColorIndex = EXcelColorIndex.红色;//红色
                    }
                }

                string countryCode = dataInfo.Table.Rows[i]["国家"].ToString();
                var country = countries.FirstOrDefault(w => w.Code == countryCode);
                if (country == null)
                {
                    ((Range)_wsh.Cells[i + 3, INFO_INDEX + 1]).Interior.ColorIndex = EXcelColorIndex.红色;
                }
                else
                {
                    string zip = dataInfo.Table.Rows[i]["邮编"].ToString().ToLower();
                    string city = dataInfo.Table.Rows[i]["城市"].ToString().ToLower();
                    string state = dataInfo.Table.Rows[i]["州"].ToString().ToLower();

                    if (resultText.Contains("distribué"))//发往法国
                    {
                        var zip0 = Tools.SubString(resultText, "(", ")", true);
                        if (!string.IsNullOrEmpty(zip0) && zip.StartsWith(zip0))
                        {
                            break;
                        }
                        break;
                    }
                    if (resultText.Contains(country.NameCN) || resultText.Contains(country.NameEN))
                    {
                        //核对邮编
                        if (!resultText.Contains(zip) && (!resultText.Contains(city) || !resultText.Contains(state)))//邮编，城市，州都不匹配
                        {
                            ((Range)_wsh.Cells[i + 3, INFO_INDEX + 1]).Interior.ColorIndex = EXcelColorIndex.橙色;
                        }
                    }
                    else//国家不对
                    {
                        ((Range)_wsh.Cells[i + 3, INFO_INDEX + 1]).Interior.ColorIndex = EXcelColorIndex.红色;
                    }
                }
            }

            app.AlertBeforeOverwriting = false;
            _wbk.SaveAs(dataInfo.ExceFile.Directory + "\\已处理\\已分析_" + dataInfo.ExceFile.Name, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            _wbk.Close(null, null, null);
            wbks.Close();
            app.Quit();
            File.Delete(excelFilename);
            //释放掉多余的excel进程
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
            app = null;
        }
    }
}
